package com.zzyl.serve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.common.utils.WechatUtil;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.serve.domain.Contract;
import com.zzyl.serve.domain.Elder;
import com.zzyl.serve.domain.FamilyMember;
import com.zzyl.serve.dto.ElderFamilyAddDto;
import com.zzyl.serve.dto.MemberLoginDto;
import com.zzyl.serve.mapper.ContractMapper;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.mapper.ElderMapper;
import com.zzyl.serve.mapper.FamilyMemberMapper;
import com.zzyl.serve.service.IElderService;
import com.zzyl.serve.service.IFamilyMemberService;
import com.zzyl.serve.vo.FamilyPageVo;
import com.zzyl.serve.vo.FamilyWithElderVo;
import com.zzyl.serve.vo.MemberLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 老人家属Service业务层处理
 *
 * @author liuyp
 * @date 2025-08-21
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private WechatUtil wechatUtil;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private IElderService elderService;


    private static final List<String> nickNamePool = List.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");
    @Autowired
    private DeviceMapper deviceMapper;


    /**
     * 微信小程序绑定老人
     * idcard，name，remark
     * @param dto
     */
    @Override
    public void add(ElderFamilyAddDto dto) {
        //获取当前微信登陆用户id
        Long familyMemberId = UserThreadLocal.getUserId();
        System.out.println("userId = " + familyMemberId);
        if (familyMemberId == null){
            throw new BaseException("当前用户没登陆");
        }

        if (dto.getRemark() == null || dto.getName() == null || dto.getIdCard() == null){
            return;
        }
        if (dto.getIdCard().length() != 18){
            return;
        }
        //根据idCard查询老人id
        Long elderId = elderMapper.selectIdByIdCard(dto.getIdCard());
        //根据老人id查询合同
        LambdaQueryWrapper<Contract> wrapper = Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId, elderId);
        Contract contract = contractMapper.selectOne(wrapper);
        //判断老人是否签了合同
        if (contract == null){
            throw new BaseException("老人没签合同");
        }
        //判断是否重复绑定过家人
        Integer count = familyMemberMapper.selectElderWithFamily(familyMemberId, elderId);
        if (count != 0){
            throw new BaseException("重复绑定老人");
        }

        //将数据插入表中
        //判断idcard是否对应这个老人
        LambdaQueryWrapper<Elder> elderWrapper = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getIdCard())
                .eq(Elder::getName, dto.getName());
        if (elderMapper.selectOne(elderWrapper) ==null ){
            throw new BaseException("身份证没有对应的老人");
        }
        familyMemberMapper.insertIntoFamilyMemberElder(dto.getRemark(), elderId,familyMemberId);
    }


    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return familyMemberMapper.deleteById(id);
    }

    @Override
    public MemberLoginVo login(MemberLoginDto dto) {
        // 1. 向微信平台发请求获取openid
        String openid = wechatUtil.getOpenid(dto.getCode());
        // 2. 向微信平台发请求获取手机号
        String phone = wechatUtil.getPhone(dto.getPhoneCode());
        // 3. 根据微信账号openid，到数据库表里查询一下
        LambdaQueryWrapper<FamilyMember> wrapper = Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = familyMemberMapper.selectOne(wrapper);
        // 4. 判断是否查到家属信息了
        if (familyMember == null) {
            familyMember = new FamilyMember();
            // 给用户设置昵称，而不是使用了用户的微信昵称。昵称：从nickNamePool里随机取一个昵称，再拼接上手机号后4位
            familyMember.setName(nickNamePool.get(new Random().nextInt(nickNamePool.size())) + phone.substring(phone.length() - 4));
            familyMember.setOpenId(openid);
            familyMember.setPhone(phone);
            save(familyMember);
        } else {
            // 如果手机号 和 数据库里的手机号不同，则需要更新手机号
            if (!phone.equals(familyMember.getPhone())) {
                familyMember.setPhone(phone);
                updateById(familyMember);
            }
        }
        // 5. 准备返回值
        MemberLoginVo vo = new MemberLoginVo();
        vo.setNickName(familyMember.getName());
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", familyMember.getId());
        claims.put("name", familyMember.getName());
        vo.setToken(tokenService.createToken(claims));
        return vo;
    }

    @Override
    public List<FamilyWithElderVo> my() {
        //查询就行
        return familyMemberMapper.familyWithElderList();
    }

    @Override
    public List<FamilyPageVo> listByPage(Integer pageNum, Integer pageSize) {
        List<FamilyPageVo> familyPageVos = deviceMapper.selectElder();
        return familyPageVos;
    }

    @Override
    public void deleteFamilyMemberElderById(Long id) {
        familyMemberMapper.deleteFamilyMemberElderById(id);
    }

}
